package com.bean;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Array;

@Slf4j
public class ArrayQueue<E> {

    private int inputIndex;

    private int queueSize;

    private E[] queueArray;


    public ArrayQueue(Class<E> c, int queueSize) {
        queueArray = (E[]) Array.newInstance(c, queueSize);
        this.queueSize = queueSize;
    }

    //元素右移动
    //进入的元素进入0位
    //inputIndex+1
    public synchronized boolean add(E inputElement) {
        if (inputIndex >= queueSize) {
            log.warn("队列已经满" + inputElement + "，无法放入.");
            return false;
        }
        log.warn("放入" + inputElement);
        rightOffset();
        queueArray[0] = inputElement;
        inputIndex++;
        return true;
    }

    //元素不移动
    //只返回inputIndex的元素
    //出了之后inputIndex-1
    public synchronized E poll() {
        E element = peek();
        if (null == element) {
            return null;
        }
        queueArray[inputIndex - 1] = null;
        inputIndex--;
        return element;

    }

    public E peek() {
        if (inputIndex == 0) {
            log.warn("队列已空无消息消费");
            return null;
        }
        E element = queueArray[inputIndex - 1];
        return element;
    }

    //数组右移位
    private void rightOffset() {
        for (int len = inputIndex; len > 0; len--) {
            if (len < queueSize) {
                E preValue = queueArray[len - 1];
                queueArray[len] = preValue;
            } else {
                log.info("Offset fail!");
            }
        }
    }
}
